package sys;
use strict;
use Time::Local;
use File::Path;
use DBI();
use IO::Dir;

use Exporter;
use base 'Exporter';

our @EXPORT = qw($dbh $table_player $table_log $table_rating $table_tournament $table_game $table_country $table_city $table_admin $table_admin_log);

open F, "<password.php" or die "not configured";
my $strcfg = join("", <F>);
close F;

die "no passwords" unless $strcfg =~ /\$dbUser\s*=\s*\"(.*?)\".*?\$dbPass\s*=\s\"(.*?)\"/gs;

my $db_user = $1;
my $db_pass = $2;
my $db_host = "mysqlserver";
my $table_prefix = "rtg_";

our $table_player = $table_prefix . "player";
our $table_log = $table_prefix . "log";
our $table_rating = $table_prefix . "trn_rating";
our $table_tournament = $table_prefix . "trn";
our $table_game = $table_prefix . "game";
our $table_country = $table_prefix . "country";
our $table_city = $table_prefix . "city";
our $table_admin = $table_prefix . "admin";
our $table_admin_log = $table_prefix . "admin_log";


if (defined($ENV{"OS"}) && $ENV{"OS"} =~ /Windows/)
{
    $db_user = "root";
    $db_pass = "";
    $db_host = "localhost";
}

our $dbh = DBI->connect("DBI:mysql:host=$db_host:database=renjune_renju", $db_user, $db_pass) or die "unable to connect to database";

my $input_file = "";
sub get_input_file()
{
    return $input_file if $input_file ne "";
    my @files = ();
    my $d = new IO::Dir "db";
    while(defined($_ = $d->read))
    {
        push @files, "./db/$_" if (-f "./db/$_" && /\.rif$/);
    }

    sort @files;
    if (@files)
    {
        $input_file = $files[-1];
    }
    else
    {
        err("no input database found");
    }
}

sub date_to_sec
{
    $_[0] =~ /^(\d\d\d\d)-(\d\d)-(\d\d)$/ or die "invalid date $_[0]";
    return timegm(0,0,0,$3,$2-1,$1);
}

sub err
{
	if (open F, ">>err_log")
    {
        print F join("", @_) . "\n";
        close F;
    }
    print qq(<font color="red">) . join("", @_) . qq(</font>);
	exit;
}

sub make_html
{
    my($what) = (@_);
    my $cgi = new CGI;
    print $cgi->header;
    print <<MH_1;
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Unofficial Renju Rating</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<LINK href="../styles/main.css" type="text/css" rel="stylesheet">
</head>
   
MH_1
  print $what;
  print "</html>";
}

1;